require('normalize.css/normalize.css');
require('styles/App.css');

import React from 'react';
import ReactDOM from 'react-dom'
import {createStore} from 'redux'

let states={
  isreversal:false
}
const reducer=(state=states,action)=>{
   switch (action.type) {
     case 'TurnPic':
       return Object.assign({},state,{isreversal:!state.isreversal});
     default:
     return state;
   }
}

let store=createStore(reducer);

//获取
var imageDataJson=require('../data/imageDatas.json');

//将图片信息转换成url路径信息函数
function getImageUrl(imageDataArr){
  for(var i in imageDataArr)  {
    var singleImageData=imageDataArr[i];
    singleImageData.imageURL=require(`../images/${singleImageData.fileName}`);

    imageDataArr[i]=singleImageData;
  }
  return  imageDataArr;
}
//将图片信息转换成url路径信息
imageDataJson=getImageUrl(imageDataJson);

class ControlUnit extends React.Component{
  constructor(...args)
  {
      super(...args);
      //this.state={isCenter:false};
  }

  clickHandle(){
    if(this.props.unitIsCenter)
    {
      store.dispatch({type:'TurnPic'});
    }
    else
    {
      let centerChange=this.props.ckickCenter;
      centerChange();
    }
  }

  render()
  {
    let classUnit="control-unit";
    //console.log(this.props.unitIsCenter);
    if(this.props.unitIsCenter)
    {
      classUnit+=" iscenter";
    }
    return (<div className={classUnit} onClick={this.clickHandle.bind(this)}>
      <p></p>
    </div>)
  }
}

class ImageFigure extends React.Component{
constructor(...args){
  super(...args);
  this.state={
    isreversal:false
  };
  store.subscribe(()=>{
          let isreversal=this.state.isreversal;
           this.setState({isreversal:!isreversal});
      })
}

clickHandle()
{
  console.log(this.props.imageStyle.isCenter);
  if(this.props.imageStyle.isCenter)
  {
    let isreversal=!this.state.isreversal;
    this.setState({isreversal:isreversal})
  }
  else
  {
    let centerChange=this.props.ckickCenter;
    centerChange();
  }
}

render(){
    let objStyle={};
    if(this.props.imageStyle.pos)
    {
      objStyle=this.props.imageStyle.pos;
    }
    if(this.props.imageStyle.degree)
    {
    objStyle['transform']='rotate('+this.props.imageStyle.degree+'deg)';
  }
    let figureClass="img-figure";
    if(this.state.isreversal)
    {
      figureClass+=" is-inverse";
    }
    if(this.props.imageStyle.isCenter)
    {
      objStyle['zIndex']=101;
    }
    

    //console.log(objStyle);
     return(
       <figure className={figureClass}  style={objStyle} onClick={this.clickHandle.bind(this)}>
         <img src={this.props.data.imageURL} alt={this.props.data.title}/>
         <figcaption>
           <h2 className="image-title">{this.props.data.title}</h2>
           <div className='image-back'>
             <p>
             {this.props.data.desc}
             </p>
          </div>
         </figcaption>
       </figure>
     );
   }
}

class AppComponent extends React.Component {
  
  constructor(...args){
    super(...args);
    this.Constant={
      centerPos:{
        left:0,
        top:0
      },
      hPosRange:{             //水平位置取值范围
        leftSecX:[0,0],
        rightSecX:[0,0],
        y:[0,0]
      },
      vPosRange:{           //竖直方向取值范围
        x:[0,0],
        topY:[0,0]
      }
    };

    this.state={imageArrangeARR:[
      {
        pos:{
          left:'0',
          top:'0'
        },
        degree:0,
        isCenter:false
      }]
    };
  }

  getPointRandom(low,hight)
  {
    return Math.ceil(Math.random()*(hight-low)+low);
  }

  get30def()
  {
    return ((Math.random()>0.5?"":"-")+ Math.ceil(Math.random()*30));
  }

  /*重新布局所有图片 */
   rearRange(centerIndex){
    // console.log(centerIndex);
     let imageArrangeARR = this.state.imageArrangeARR,
         imageArrCenter=imageArrangeARR.splice(centerIndex,1);

         imageArrCenter[0].pos=this.Constant.centerPos;
         imageArrCenter[0].isCenter=true;
         imageArrCenter[0].degree=0;
     let imageArrTopLength=Math.ceil(Math.random() * 2);
     let imageArrTopIndex=Math.ceil(Math.random() * imageArrangeARR.length-imageArrTopLength);
     let imageArrTop=imageArrangeARR.splice(imageArrTopIndex,imageArrTopLength);

     let imageArrleft=[],imageArrRight=[];
     for(let i=0,j=imageArrangeARR.length/2;i<imageArrangeARR.length;i++)
     {
       if(i<j)
       {
         imageArrleft.push(imageArrangeARR[i]);
       }
       else
       {
         imageArrRight.push(imageArrangeARR[i])
       }
     }

     for(let value in imageArrTop)
     {
       let leftPoint=this.getPointRandom(this.Constant.vPosRange.x[0],this.Constant.vPosRange.x[1]),
           topPoint=this.getPointRandom(this.Constant.vPosRange.topY[0],this.Constant.vPosRange.topY[1]);
           imageArrTop[value]={
             pos:{
               left:leftPoint,
               top:topPoint
             },
             degree:this.get30def(),
             isCenter:false
           }
     }
     

     for(let value in imageArrleft)
     {
       let leftPoint=this.getPointRandom(this.Constant.hPosRange.leftSecX[0],this.Constant.hPosRange.leftSecX[1]),
           topPoint=this.getPointRandom(this.Constant.hPosRange.y[0],this.Constant.hPosRange.y[1]);
           imageArrleft[value]={
             pos:{
               left:leftPoint,
               top:topPoint
             },
             degree:this.get30def(),
             isCenter:false
           }
     }

     for(let value in imageArrRight)
     {
       let leftPoint=this.getPointRandom(this.Constant.hPosRange.rightSecX[0],this.Constant.hPosRange.rightSecX[1]),
           topPoint=this.getPointRandom(this.Constant.hPosRange.y[0],this.Constant.hPosRange.y[1]);
           imageArrRight[value]={
             pos:{
               left:leftPoint,
               top:topPoint
             },
             degree:this.get30def(),
             isCenter:false
           }
     }
     imageArrangeARR=[...imageArrleft,...imageArrRight];
     if(imageArrTopLength>0)
     {
       imageArrangeARR.splice(imageArrTopIndex,0,...imageArrTop);
     }
     imageArrangeARR.splice(centerIndex,0,...imageArrCenter);
    //console.log(imageArrangeARR);
    this.setState({imageArrangeARR:imageArrangeARR});
   }
   
   clickCenterHandle(index)
   {
     return function(){
       this.rearRange(index);
     }
   }

   componentDidMount()   {

     //获取舞台的大小
     let stageDom = ReactDOM.findDOMNode(this.refs.stage),
     stageDOMWidth = stageDom.scrollWidth,
     stageDOMHeight = stageDom.scrollHeight,
     halfStageW =  Math.ceil(stageDOMWidth / 2),
     halfStageH = Math.ceil(stageDOMHeight / 2);

     //获取imagefiguredaxiao
     let imageFigureDOM = ReactDOM.findDOMNode(this.refs.imageFigure0),
     imageFigureW = imageFigureDOM.scrollWidth,
     imageFigureH = imageFigureDOM.scrollHeight,
     halfImageFigureW = Math.ceil(imageFigureW / 2),
     halfImageFigureH = Math.ceil(imageFigureH / 2);
     this.Constant.centerPos.left = halfStageW - halfImageFigureW;
     this.Constant.centerPos.top = halfStageH - halfImageFigureH;

     this.Constant.hPosRange.leftSecX[0] = 0 - halfImageFigureW;
     this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImageFigureW * 3;
     this.Constant.hPosRange.rightSecX[0]=halfStageW + halfImageFigureW;
     this.Constant.hPosRange.rightSecX[1] = stageDOMWidth - halfImageFigureW
     this.Constant.hPosRange.y[0] = 0 - halfImageFigureH;
     this.Constant.hPosRange.y[1] = stageDOMHeight - halfImageFigureH;
     this.Constant.vPosRange.x[0] = halfStageW - imageFigureW;
     this.Constant.vPosRange.x[1] = halfStageW;
     this.Constant.vPosRange.topY[0] = 0 - halfImageFigureH;
     this.Constant.vPosRange.topY[1] = halfStageH - halfImageFigureH * 3;
     this.rearRange(0);
   }

   
  render() {
    //let controllerUnit=[];
    let imageFigures=[];
    let controlUnits=[];
    imageDataJson.forEach(function(value,index){
      if(!this.state.imageArrangeARR[index]){
        this.state.imageArrangeARR[index]={
          pos:{
          left:'0',
          top:'0'
        },
        degree:0,
        isCenter:false
        }
      }

       imageFigures.push(<ImageFigure data={value} ref={`imageFigure${index}`} key={index} imageStyle={this.state.imageArrangeARR[index]} ckickCenter={this.clickCenterHandle(index).bind(this)}/>)
       controlUnits.push(<ControlUnit key={index} unitIsCenter={this.state.imageArrangeARR[index].isCenter} ckickCenter={this.clickCenterHandle(index).bind(this)}></ControlUnit>);
         
  }.bind(this)
    );
    return (
      <section className='stage' ref='stage'>
        <section className='img-sec'>
           {imageFigures}
        </section>
        <nav className="controller-nav">
          {controlUnits}
        </nav>
      </section>
    );
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;
